package com.yaodian100.ec.generate.service.impl;

import java.io.File;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.math.NumberUtils;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.ec.generate.entity.ViewPromotionAdvertise;
import com.yaodian100.ec.generate.service.GenerateNotifyService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.shelf.entity.ViewShelf;

public class IdxSaleV5Generater extends AbstractAdvGenerater {
	
	private final GenerateServiceImpl generateServiceImpl;
	private final GenerateNotifyService generateNotifyService;
	
	IdxSaleV5Generater(GenerateServiceImpl impl,GenerateNotifyService generateNotifyService) {
		this.generateServiceImpl = impl;
		this.generateNotifyService = generateNotifyService;
	}
	
	public boolean generaterIdxSaleV5() throws Exception {
		try {
			String advType = "IDX_SALE_V5";
			String cateId = "IDX";
			int PROD_SIZE = 8;
			
			// 查寻最新的广告
			CommonCriteria criteria = new CommonCriteria();
			criteria.addEq("advType", advType);
			List<ViewPromotionAdvertise> viewPromotionAdvs = generateServiceImpl.getViewPromotionAdvertiseDao().getList(criteria, new String[] { "modifyDate desc" });
			
			if (viewPromotionAdvs.size() > 0) {
				
				// 建立folder
				boolean mkDirsuccess = this.generateServiceImpl.mkGenerateHtmlDir(advType, cateId);
				if (!mkDirsuccess) {
					throw new RuntimeException("建立 html 目錄失敗");
				}
				
				// 删除档案
				generateServiceImpl.deleteFiles(ServerValue.getFrontContentHtmlPath() + cateId, advType);
				
				Reader reader = null;
				Properties prop = null;
				
				// 收集上架的广告id
				List<Long> upList = new ArrayList<Long>();
				
				// 收集商品pid
				List<String> pids = null;
				
				// 商品map
				Map<String, Product> products = new HashMap<String, Product>();
				
				// 上架檔map
				Map<String, ViewShelf> shelfs = new HashMap<String, ViewShelf>();
				List<ViewShelf> viewShelfList = null;
				
				int viewNo = 0, cnt1 = 1, cnt2 = 1, cnt3 = 1, cnt4 = 1, cnt5 = 1;
				
				for (int i = 0; i < viewPromotionAdvs.size(); i++) {
					// 读取properties
					ViewPromotionAdvertise viewPromotionAdv = viewPromotionAdvs.get(i);
					prop = new Properties();
					reader = new StringReader(viewPromotionAdv.getContents());
					prop.load(reader);
					reader.close();
					
					String site = "";
					if(1 == NumberUtils.toInt(viewPromotionAdv.getAdvTarget())) {
						if(cnt1 <= 3)
							upList.add(Long.parseLong(String.valueOf(viewPromotionAdv.getId())));
						else 
							continue;
						site = "F";
						viewNo = cnt1++;
					} else if(2 == NumberUtils.toInt(viewPromotionAdv.getAdvTarget())) {
						if(cnt2 <= 3)
							upList.add(Long.parseLong(String.valueOf(viewPromotionAdv.getId())));
						else 
							continue;
						site = "S";
						viewNo = cnt2++;
					} else if(3 == NumberUtils.toInt(viewPromotionAdv.getAdvTarget())) {
						if(cnt3 <= 3)
							upList.add(Long.parseLong(String.valueOf(viewPromotionAdv.getId())));
						else 
							continue;
						site = "L";
						viewNo = cnt3++;
					} else if(4 == NumberUtils.toInt(viewPromotionAdv.getAdvTarget())) {
						if(cnt4 <= 3)
							upList.add(Long.parseLong(String.valueOf(viewPromotionAdv.getId())));
						else 
							continue;
						site = "H";
						viewNo = cnt4++;
					} else if(5 == NumberUtils.toInt(viewPromotionAdv.getAdvTarget())) {
						if(cnt5 <= 3)
							upList.add(Long.parseLong(String.valueOf(viewPromotionAdv.getId())));
						else 
							continue;
						site = "D";
						viewNo = cnt5++;
					}
					
					pids = new ArrayList<String>();
					
					for(int j = 1; j <= PROD_SIZE; j++) { // 一组广告8个商品
						String prodId = prop.getProperty("prodId" + j );
						pids.add(prodId);
					}
					
					if(pids.size() > 0) {
						// 取得商品
						CommonCriteria prdtCriteria = new CommonCriteria();
						prdtCriteria.addIn("productId", pids);
						products = generateServiceImpl.getProductDao().getMap("productId", prdtCriteria, null);
						
						// 取得上架档
						viewShelfList = generateServiceImpl.getShelfService().getPublishShelfs(null, pids.toArray(new String[0]));
						if (!viewShelfList.isEmpty()) {
							for (ViewShelf shelf : viewShelfList) {
								shelfs.put(shelf.getProductId(), shelf);
							}
						}
						
						// 检核商品并寄发错误通知信
						generateNotifyService.sendNotificationForProductIdsWithProblem(Long.parseLong("0"), pids
								, viewPromotionAdv.getAdvType(), viewPromotionAdv.getAdvName());
					}
					
					Map<String, Object> m = new HashMap<String, Object>();
					m.put("prop", prop);
					m.put("products", products);
					m.put("shelfs", shelfs);
					m.put("advType", advType);
					m.put("advTarget", viewPromotionAdv.getAdvTarget());
					m.put("contentPath", ServerValue.getFrontContextPath());
					
					StringBuilder htmlFilePath;
					htmlFilePath = new StringBuilder();
					htmlFilePath.append(ServerValue.getFrontContentHtmlPath())
							.append(cateId)
							.append(File.separator)
							.append(advType)
							.append("_")
							.append(site)
							.append("_")
							.append(viewNo)
							.append(".html");
					
					FileUtils.writeStringToFile(new File(htmlFilePath.toString()), generateServiceImpl.getTemplateService().format("static_Sale_V5", m));
				}
				if (upList.size() > 0) { // 修改上架广告status
					generateServiceImpl.updateAdvStatus(advType, upList);
				}
				
			}
		} catch (Exception e) {
//			logger.error("generaterIdxHotSaleV5 exception:{}", e.fillInStackTrace());
			return false;
		}
		
		return true;
	}
	
	public boolean generaterIdxSaleV5(String domain, String advType) throws Exception {
		try {
			boolean isIdx = false;
			//String advType = "PCL_SALE_V5";
			// 主站advType
			String advType2 = "IDX_SALE_V5";
			String cateId = domain + File.separator + "IDX";
			int PROD_SIZE = 8;
			
			// 查寻最新的广告
			CommonCriteria criteria = new CommonCriteria();
			criteria.addEq("advType", advType);
			List<ViewPromotionAdvertise> viewPromotionAdvs = generateServiceImpl.getViewPromotionAdvertiseDao().getList(criteria, new String[] { "modifyDate desc" });
			
			// 如果没资料，抓yaodian100的
			if( viewPromotionAdvs.size() == 0 ) {
				isIdx = true;
				criteria = new CommonCriteria();
				criteria.addEq("advType", advType2);
				viewPromotionAdvs = generateServiceImpl.getViewPromotionAdvertiseDao().getList(criteria, new String[] { "modifyDate desc" });
			}
			
			if (viewPromotionAdvs.size() > 0) {
				
				// 建立folder
				boolean mkDirsuccess = this.generateServiceImpl.mkGenerateHtmlDir(advType, cateId);
				if (!mkDirsuccess) {
					throw new RuntimeException("建立 html 目錄失敗");
				}
				
				// 删除档案
				generateServiceImpl.deleteFiles(ServerValue.getFrontContentHtmlPath() + cateId, advType);
				
				Reader reader = null;
				Properties prop = null;
				
				// 收集上架的广告id
				List<Long> upList = new ArrayList<Long>();
				
				// 收集商品pid
				List<String> pids = null;
				
				// 商品map
				Map<String, Product> products = new HashMap<String, Product>();
				
				// 上架檔map
				Map<String, ViewShelf> shelfs = new HashMap<String, ViewShelf>();
				List<ViewShelf> viewShelfList = null;
				
				int viewNo = 0, cnt1 = 1, cnt2 = 1, cnt3 = 1, cnt4 = 1, cnt5 = 1;
				
				for (int i = 0; i < viewPromotionAdvs.size(); i++) {
					// 读取properties
					ViewPromotionAdvertise viewPromotionAdv = viewPromotionAdvs.get(i);
					prop = new Properties();
					reader = new StringReader(viewPromotionAdv.getContents());
					prop.load(reader);
					reader.close();
					
					String site = "";
					if(1 == NumberUtils.toInt(viewPromotionAdv.getAdvTarget())) {
						if(cnt1 <= 3)
							upList.add(Long.parseLong(String.valueOf(viewPromotionAdv.getId())));
						else 
							continue;
						site = "F";
						viewNo = cnt1++;
					} else if(2 == NumberUtils.toInt(viewPromotionAdv.getAdvTarget())) {
						if(cnt2 <= 3)
							upList.add(Long.parseLong(String.valueOf(viewPromotionAdv.getId())));
						else 
							continue;
						site = "S";
						viewNo = cnt2++;
					} else if(3 == NumberUtils.toInt(viewPromotionAdv.getAdvTarget())) {
						if(cnt3 <= 3)
							upList.add(Long.parseLong(String.valueOf(viewPromotionAdv.getId())));
						else 
							continue;
						site = "L";
						viewNo = cnt3++;
					} else if(4 == NumberUtils.toInt(viewPromotionAdv.getAdvTarget())) {
						if(cnt4 <= 3)
							upList.add(Long.parseLong(String.valueOf(viewPromotionAdv.getId())));
						else 
							continue;
						site = "H";
						viewNo = cnt4++;
					} else if(5 == NumberUtils.toInt(viewPromotionAdv.getAdvTarget())) {
						if(cnt5 <= 3)
							upList.add(Long.parseLong(String.valueOf(viewPromotionAdv.getId())));
						else 
							continue;
						site = "D";
						viewNo = cnt5++;
					}
					
					pids = new ArrayList<String>();
					
					for(int j = 1; j <= PROD_SIZE; j++) { // 一组广告8个商品
						String prodId = prop.getProperty("prodId" + j );
						pids.add(prodId);
					}
					
					if(pids.size() > 0) {
						// 取得商品
						CommonCriteria prdtCriteria = new CommonCriteria();
						prdtCriteria.addIn("productId", pids);
						products = generateServiceImpl.getProductDao().getMap("productId", prdtCriteria, null);
						
						// 取得上架档
						viewShelfList = generateServiceImpl.getShelfService().getPublishShelfs(null, pids.toArray(new String[0]));
						if (!viewShelfList.isEmpty()) {
							for (ViewShelf shelf : viewShelfList) {
								shelfs.put(shelf.getProductId(), shelf);
							}
						}
						
						// 检核商品并寄发错误通知信
//						generateNotifyService.sendNotificationForProductIdsWithProblem(Long.parseLong("0"), pids
//								, viewPromotionAdv.getAdvType(), viewPromotionAdv.getAdvName());
					}
					
					Map<String, Object> m = new HashMap<String, Object>();
					m.put("prop", prop);
					m.put("products", products);
					m.put("shelfs", shelfs);
					if( isIdx )
						m.put("advType", advType2);
					else 
						m.put("advType", advType);
					m.put("advTarget", viewPromotionAdv.getAdvTarget());
					m.put("contentPath", ServerValue.getFrontContextPath());
					
					StringBuilder htmlFilePath;
					htmlFilePath = new StringBuilder();
					htmlFilePath.append(ServerValue.getFrontContentHtmlPath())
							.append(cateId)
							.append(File.separator)
							.append(advType2)
							.append("_")
							.append(site)
							.append("_")
							.append(viewNo)
							.append(".html");
					
					FileUtils.writeStringToFile(new File(htmlFilePath.toString()), generateServiceImpl.getTemplateService().format("static_Sale_V5", m).replaceAll("http://www.yaodian100.com", ""));
				}
				if (upList.size() > 0) { // 修改上架广告status
					generateServiceImpl.updateAdvStatus(advType, upList);
				}
				
			}
		} catch (Exception e) {
//			logger.error("generaterIdxHotSaleV5 exception:{}", e.fillInStackTrace());
			return false;
		}
		
		return true;
	}
}
